from rest_framework import serializers
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password
from .models import User, UserBadge, Badge, UserMessage, PendingUserRegistration


class UserRegistrationSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(write_only=True, min_length=6)
    
    class Meta:
        model = User
        fields = ['email', 'nickname', 'password']
        
    def validate_email(self, value):
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError("This email has already been registered")
        return value
        
    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data['password'])
        user = super().create(validated_data)
        
        # 为新注册用户自动分配ID为1的徽章
        try:
            default_badge = Badge.objects.get(badge_id=1)
            UserBadge.objects.create(
                user=user,
                badge=default_badge,
                is_show=True  # 默认展示
            )
        except Badge.DoesNotExist:
            # 如果ID为1的徽章不存在，可以记录日志或忽略
            pass
        
        return user


class UserLoginSerializer(serializers.Serializer):
    """用户登录序列化器"""
    email = serializers.EmailField()
    password = serializers.CharField()
    
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        
        if email and password:
            user = authenticate(username=email, password=password)
            if not user:
                raise serializers.ValidationError("Email or password error")
            if not user.is_active:
                raise serializers.ValidationError("The user account has been disabled")
            attrs['user'] = user
        else:
            raise serializers.ValidationError("Email and password must be provided")
        
        return attrs


class BadgeSerializer(serializers.ModelSerializer):
    """徽章序列化器"""
    class Meta:
        model = Badge
        fields = ['badge_id', 'name', 'description', 'img']


class UserBadgeSerializer(serializers.ModelSerializer):
    """用户徽章序列化器"""
    badge = BadgeSerializer(read_only=True)
    
    class Meta:
        model = UserBadge
        fields = ['id', 'badge', 'get_time', 'is_show']


class UserInfoSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    userId = serializers.CharField(source='user_id', read_only=True)
    nickName = serializers.CharField(source='nickname')
    sex = serializers.IntegerField(source='gender')
    personDescription = serializers.CharField(source='signature', allow_blank=True)
    joinTime = serializers.DateTimeField(source='register_time', format='%Y-%m-%d', read_only=True)
    lastLoginTime = serializers.DateTimeField(source='last_login_time', format='%Y-%m-%d %H:%M', read_only=True)
    badgeCount = serializers.SerializerMethodField()
    postCount = serializers.SerializerMethodField()
    commentCount = serializers.SerializerMethodField()
    badgeShow = serializers.SerializerMethodField()
    hasTopPostPermission = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = [
            'userId', 'email', 'nickName', 'avatar', 'sex', 'personDescription',
            'joinTime', 'lastLoginTime', 'institution', 'badgeCount', 'postCount', 'commentCount',
            'badgeShow', 'hasTopPostPermission'
        ]
        
    def get_badgeCount(self, obj):
        return UserBadge.objects.filter(user=obj).count()
        
    def get_postCount(self, obj):
        return obj.article_set.count()
        
    def get_commentCount(self, obj):
        return obj.comment_set.count()
        
    def get_badgeShow(self, obj):
        try:
            user_badge = UserBadge.objects.filter(user=obj, is_show=True).first()
            if user_badge:
                return {
                    'id': user_badge.id,
                    'badgeId': user_badge.badge.badge_id,
                    'name': user_badge.badge.name,
                    'img': user_badge.badge.img,
                    'description': user_badge.badge.description
                }
        except:
            pass
        return None
    
    def get_hasTopPostPermission(self, obj):
        """检查用户是否有置顶权限"""
        # 管理员和超级用户自动拥有权限
        if obj.is_staff or obj.is_superuser:
            return True
        
        # 检查是否有置顶权限记录
        from .models import TopPostPermission
        return TopPostPermission.objects.filter(
            user=obj,
            is_active=True
        ).exists()


class UserUpdateSerializer(serializers.ModelSerializer):
    """用户信息更新序列化器"""
    nickName = serializers.CharField(source='nickname')
    sex = serializers.IntegerField(source='gender')
    personDescription = serializers.CharField(source='signature', allow_blank=True)
    avatar = serializers.URLField(required=False, allow_blank=True)
    showBadge = serializers.IntegerField(write_only=True, required=False)
    
    class Meta:
        model = User
        fields = ['nickName', 'sex', 'personDescription', 'avatar', 'showBadge']
        
    def validate_avatar(self, value):
        """验证头像URL"""
        if value is None:
            return value
            
        # 如果传入空字符串，表示要移除头像，设置为默认头像
        if value == "":
            return 'https://campus-nexus.oss-cn-guangzhou.aliyuncs.com/avatar/default/default.jpg'
            
        # 如果传入了URL，验证是否为有效的URL格式
        if value and not value.startswith(('http://', 'https://')):
            raise serializers.ValidationError("Avatar must be a valid URL address")
            
        return value
        
    def update(self, instance, validated_data):
        show_badge = validated_data.pop('showBadge', None)
        
        # 处理头像字段
        if 'avatar' in validated_data:
            avatar_value = validated_data['avatar']
            if avatar_value is None:
                # 如果前端没有提交avatar字段或提交了null，保持原有头像不变
                validated_data.pop('avatar')
        
        # 更新用户基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        
        # 更新展示徽章
        if show_badge is not None:

            UserBadge.objects.filter(user=instance, is_show=True).update(is_show=False)

            if show_badge > 0:
                UserBadge.objects.filter(id=show_badge, user=instance).update(is_show=True)
                
        return instance


class UserMessageSerializer(serializers.ModelSerializer):
    """用户消息序列化器"""
    messageId = serializers.IntegerField(source='message_id')
    articleId = serializers.CharField(source='article_id')
    articleTitle = serializers.CharField(source='article_title')
    commentId = serializers.IntegerField(source='comment_id')
    sendUserId = serializers.CharField(source='send_user_id')
    sendNickName = serializers.CharField(source='send_nick_name')
    sendUserAvatar = serializers.SerializerMethodField()
    messageType = serializers.IntegerField(source='message_type')
    content = serializers.SerializerMethodField()
    message = serializers.SerializerMethodField()
    time = serializers.DateTimeField(source='create_time', format='%Y-%m-%d %H:%M:%S')
    readStatus = serializers.IntegerField(source='status')
    
    class Meta:
        model = UserMessage
        fields = [
            'messageId', 'articleId', 'articleTitle', 'commentId', 'sendUserId',
            'sendNickName', 'sendUserAvatar', 'messageType', 'content', 'message', 'time', 'readStatus'
        ]
        
    def get_sendUserAvatar(self, obj):
        """获取发送用户的头像"""
        if obj.send_user_id:
            try:
                from .models import User
                user = User.objects.get(user_id=obj.send_user_id)
                return user.avatar
            except User.DoesNotExist:
                pass
        return 'https://campus-nexus.oss-cn-guangzhou.aliyuncs.com/avatar/default/default.jpg'
    
    def get_content(self, obj):
        """获取评论内容"""
        if obj.comment_id:
            try:
                from apps.comments.models import Comment
                comment = Comment.objects.get(comment_id=obj.comment_id)
                return comment.content
            except Comment.DoesNotExist:
                pass
        # 如果没有评论ID或评论不存在，返回消息内容
        return obj.message_content
    
    def get_message(self, obj):
        """获取用户自己的评论内容"""
        # 对于回复评论类型的消息（message_type=2），需要找到被回复的评论内容
        if obj.message_type == 2 and obj.comment_id:
            try:
                from apps.comments.models import Comment
                # 获取新创建的回复评论
                new_comment = Comment.objects.get(comment_id=obj.comment_id)
                
                # 通过新评论的p_comment_id找到被回复的原始评论
                if new_comment.p_comment_id and new_comment.p_comment_id != 0:
                    try:
                        original_comment = Comment.objects.get(comment_id=new_comment.p_comment_id)
                        # 返回被回复的原始评论内容
                        return original_comment.content
                    except Comment.DoesNotExist:
                        pass
            except Comment.DoesNotExist:
                pass
        
        # 对于回复帖子类型的消息（message_type=1），返回文章标题
        if obj.message_type == 1 and obj.article_title:
            return obj.article_title
        
        # 其他情况返回原始消息内容
        return obj.message_content


class PendingUserRegistrationSerializer(serializers.ModelSerializer):
    """外来用户注册申请序列化器"""
    password = serializers.CharField(write_only=True, min_length=6)
    
    class Meta:
        model = PendingUserRegistration
        fields = ['email', 'nickname', 'password', 'institution', 'support']
        
    def validate_email(self, value):
        # 检查邮箱是否已经在用户表中存在
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError("This email is already registered")
        
        # 检查是否已经有待审核的申请
        if PendingUserRegistration.objects.filter(email=value, status=0).exists():
            raise serializers.ValidationError("There is already a pending registration for this email")
        
        return value
        
    def validate_institution(self, value):
        # 验证机构名称不能为空
        if not value or not value.strip():
            raise serializers.ValidationError("Institution name cannot be empty")
        return value.strip()
        
    def create(self, validated_data):
        # 加密密码
        validated_data['password'] = make_password(validated_data['password'])
        return super().create(validated_data)